package models;

import com.mysql.jdbc.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import system.Model;

/**
 * Class Log
 * @author Rezan Achmad
 */
public class Log extends Model {

    public int id;
    public int user_id;
    public String time;
    public String query;

    public Log() {
        this("");
    }

    public Log(String query) {
        // Set user id
        this.user_id = 0;
        try {
            this.user_id = (Integer) request.getSession(true).getAttribute("user_id");
        } catch (Exception e) {
        }

        // Set time
        this.time = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(Calendar.getInstance().getTime());

        // Set query and escape string
        this.query = query.replaceAll("'", "").replaceAll("\\\"", "");
        System.out.println(this.query);
    }

    @Override
    public boolean add() {
        // Build SQL
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO `log`(`user_id`,`time`, `query`) VALUES('").append(user_id).append("', '").append(time).append("', '").append(query).append("');");

        // Create statement
        Statement statement = getStatement();

        try {
            // Insert
            statement.executeUpdate(sql.toString(), Statement.RETURN_GENERATED_KEYS);

            // Set Id
            ResultSet result = statement.getGeneratedKeys();
            if (result.next()) {
                id = result.getInt(1);
            }
        } catch (SQLException e) {
            // Something error
            Logger.getLogger(Pesanan.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }

        return true;
    }

    public static boolean add(String query) {
        return (new Log(query)).add();
    }

    @Override
    public void setAttributes(ResultSet rs) throws SQLException {
    }

    @Override
    public boolean validate() {
        return true;
    }

    @Override
    public void initAttributesLabel() {
    }
}
